package com.zgh.util;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

public class QiniuUtil {

    // 在七牛注册后获得的accessKey和secretKey（改为自己的）
    private static String accessKey = "IFJ-uzk49VH8APvn6fhRaCu3MAqAS_oYTHlXRO4T";
    private static String secretKey = "PEsvtd2NcgvybRLXCpl3PVbH1DVLtdRT3oqoiC7Z";
    private static String bucket = "pkxtest";
    private static final String prix = "http://rc4fmb32y.hd-bkt.clouddn.com/";
    //潘凯鑫
//    private static String accessKey = "IFJ-uzk49VH8APvn6fhRaCu3MAqAS_oYTHlXRO4T";
//    private static String secretKey = "PEsvtd2NcgvybRLXCpl3PVbH1DVLtdRT3oqoiC7Z";
//    private static String bucket = "pkxtest"; // 七牛空间名（改为自己的）

    ////郑高和
    //private static String accessKey = "eP5Pa6jObXo0uz7gsdmyVlSL2ntywNz4lt7c5s5v";
    //private static String secretKey = "fPl70I3h9lPlW_2ER23QfCdo-91GZ0f3B-bht-1t";
    //private static String bucket = "miniprogram-space-2"; // 七牛空间名（改为自己的）
    //private static final String prix = "http://rcsvrfe40.hd-bkt.clouddn.com/";
    // 主函数用来测试
    public static void main(String[] args) {
        String token = getToken("test.jpg");
        System.out.println(token);
    }

    // 获取覆盖同名文件的上传凭证
    public static String getToken(String key) {
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket, key, 36000000, null, true); // 生成覆盖相同key文件的上传Token
        return upToken;
    }

    // 获取普通上传凭证
    public static String getUploadToken() {
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket, null, 36000000, null, true);
        return upToken;
    }

    // 删除七牛中指定key的文件
    public static boolean delFile(String key) {
        // 构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, key);
            return true;
        } catch (QiniuException ex) {
            // 如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
            return false;
        }
    }

    // 批量删除七牛文件
    public static boolean delFileList(String[] keyList) {
        Configuration cfg = new Configuration(Zone.zone0());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(bucket, keyList);
            Response response = bucketManager.batch(batchOperations);
            BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
            for (int i = 0; i < keyList.length; i++) {
                BatchStatus status = batchStatusList[i];
                String key = keyList[i];
                System.out.print(key + "\t");
                if (status.code == 200) {
                    System.out.println("delete success");
                } else {
                    System.out.println(status.data.error);
                }
            }
            return true;
        } catch (QiniuException ex) {
            System.err.println(ex.response.toString());
            return false;
        }
    }

    //上传图片
    public static String upload2Qiniu(MultipartFile file, String fileName){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(file.getBytes(), fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return prix+putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            try {
                System.err.println(r.bodyString());
                return null;
            } catch (QiniuException ex2) {
                //ignore
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
